<?php

class Loader {
	
	public
	$controller,
	$action,
	$params,
	$zats;
	
	
	/**
	 * Construtor.
	 * Registra a fun��o loader para realizar o carregamento din�nimo das classes.
	 */
	public function __construct() {
		spl_autoload_register(array($this, 'loader'));
	}
	
	
	
	private function loader($className) {
		require_once "$className.php";
	}

	
	/**
	 * M�todo que captura a URL, define o controller, a action, e os par�metros para a aplica��o.
	 * @
	 * @access private
	 * @return void
	 */
	private function getUrl(){
		
		$url = $_SERVER['REQUEST_URI'];
		$url = explode('/', $url);
		
		foreach ($url as $u){
			if(!empty($u))
				$data[] = $u;			
		}
		
		if(isset($data)){		
			$this->controller = (strtolower($data[0]) == 'admin') ? ucfirst($data[0])."Controller" : "IndexController";
			if($this->controller == 'admin'){
				$this->action = (empty($data[1])) ? "indexAction" : $data[1]."Action";
			}
			else{
				$this->action = (empty($data[0])) ? "indexAction" : $data[0]."Action";
			}
			
			$params = "";
			
			unset($data[0]);
			unset($data[1]);
			
			foreach($data as $d){
				$params[] = $d."Action";
			}
			
			$this->params = $params;

		}
		else{
			$this->controller = "IndexController";
			$this->action = "indexAction";
		}
		
		
		return $this;
		
	}
	
	
	/**
	 * Carrega o controller e instancia um objeto do mesmo.
	 */
	private function loadController(){
		$this->getUrl();
		$zats = new $this->controller();
		return $zats;
	}
	
	
	/**
	 * Carrega uma action
	 * @throws Exception
	 */
	private function loadAction(){
		//$zats = $this->loadController();
		$action = $this->action;
		
		
		try{
			if(method_exists($this->controller, $this->action)){
				$this->loadController()->$action();
			}
			else{
				throw new Exception();
			}
		}
		catch (Exception $e){
			$this->loadController()->indexAction('page');
		}
	}
	
	/**
	 * Carrega o controller e action
	 */
	public function run(){
		$this->getUrl();
		$this->loadAction();
	}

}


$loader = new Loader();
$loader->run();